﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sita.Data.Context;
using Sita.Entities;
using Sita.Data.Core;

namespace Sita.Data.Repositories
{
    public class ProviderRepository : GenericRepository<Provider>
    {
        public ProviderRepository() :
            base(new SitaContext())
        { }

        public IList<Provider> GetPaginatedByBusinessUnitID(int businessUnitID, int pageIndex, int pageSize, string sortColumn, bool ascending, out int totalRows)
        {
            RepositoryHelper<Provider> Helper = new RepositoryHelper<Provider>();
            var OrderByExpr = Helper.GetOrderExpression(sortColumn);

            IQueryable<Provider> ReturnSet;

            ReturnSet = (base.StoreContext as ISitaContext).Providers
                .Where(p => p.BusinessUnitID == businessUnitID)
                .Select(p => p);

            totalRows = ReturnSet.Count();

            return (ascending)
                                ?
                                    ((IOrderedQueryable<Provider>)System.Linq.Queryable.OrderBy(ReturnSet, OrderByExpr))
                                        .Skip(pageIndex * pageSize)
                                        .Take(pageSize)
                                        .ToList()
                                :
                                    ((IOrderedQueryable<Provider>)System.Linq.Queryable.OrderByDescending(ReturnSet, OrderByExpr))
                                        .Skip(pageIndex * pageSize)
                                        .Take(pageSize)
                                        .ToList();
        }

        public IList<Provider> GetAllByBusinessUnitID(int buID)
        {
            RepositoryHelper<Provider> Helper;
            Helper = new RepositoryHelper<Provider>();
            var OrderByExpr = Helper.GetOrderExpression("Name");

            IQueryable<Provider> ReturnSet;
            ReturnSet = (base.StoreContext as ISitaContext).Providers
                .Where(p => p.BusinessUnitID == buID)
                .Select(p => p);

            return ((IOrderedQueryable<Provider>)System.Linq.Queryable.OrderBy(ReturnSet, OrderByExpr))
                .ToList();
        }

        public Provider GetByIDWithReplacements(int ProviderID)
        {
            Provider ReturnSet;
            ReturnSet = (base.StoreContext as ISitaContext).Providers
                .Where(p => p.ProviderID == ProviderID)
                .Include("Replacements")
                .SingleOrDefault();

            return ReturnSet;
        }
    }
}